package controllers

import (
	"fmt"
	"goetl/g"
	"goetl/models"
	"goetl/services"
	"goetl/utils"
	"os"
	"time"

	"github.com/astaxie/beego"
	"github.com/snluu/uuid"
)

const DESIGN_FOLDER_NAME string = "<Design Time>"

type FlowController struct {
	beego.Controller
}

// @router /services/Flow/GetNodes [get]
func (c *FlowController) GetNodes() {

	flowId := c.GetString("flowId")
	var flowStepLinks []*models.FlowStepLink
	err, flow := services.ConfigurationService.FindFlow(flowId)
	if err == nil {

		err, flowStepLinks = services.ConfigurationService.FindFlowStepLinks(flowId)
	}

	if err == nil {
		c.Data["json"] = map[string]interface{}{
			"flow": flow, "flowStepLinks": flowStepLinks}
		c.ServeJSON()
	}
}

// @router /services/Flow/RunFlow [post]
func (c *FlowController) RunFlow() {
	var executionId string
	flowId := c.GetString("flowId")

	hostname, _ := os.Hostname()
	utils.ConsoleLogs.Info("Run Flow at HostName : %s", hostname)
	login_id := ((c.GetSession("user")).(models.User)).LoginId
	AGENT_NAME := fmt.Sprintf("<%s on %s>", login_id, hostname)
	utils.ConsoleLogs.Info("AGENT_NAME : %s", AGENT_NAME)
	var agent models.Agent
	_, agents := services.OperationsService.FindAgentsByName(AGENT_NAME)
	if len(agents) > 0 {
		agent = *agents[0]

	} else {

		_, folder := services.ConfigurationService.FindFirstFolderWithName(DESIGN_FOLDER_NAME, "AGENT")
		if folder.Id == "" {
			folder = *(&models.Folder{Id: uuid.Rand().Hex(), Type: "AGENT", Name: DESIGN_FOLDER_NAME, Deleted: 0, CreateBy: login_id, CreateTime: time.Now()})

			services.ConfigurationService.SaveFolder(folder)
		}

		agent = models.Agent{Id: uuid.Rand().Hex(), Name: AGENT_NAME, FolderId: &folder, Deleted: 0, CreateBy: login_id, CreateTime: time.Now()}

		services.ConfigurationService.SaveAgent(agent)
	}

	_, flow := services.ConfigurationService.FindFlow(flowId)

	_, deploy := services.OperationsService.GetAgentDeploymentFor(agent, flow)

	agentRuntime := g.MyAgentManager.GetAgentRuntime(agent.Id)

	if deploy.Id == "" {
		agentRuntime.DeployByAgentDeployment(deploy)
	}

	if flow.WebService == 0 {
		executionId = agentRuntime.ScheduleNow(login_id, deploy, nil)
	}

	c.Data["json"] = map[string]interface{}{
		"result": true, "executionId": executionId}
	c.ServeJSON()
}
